<template>
  <el-dialog width="80%" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <ele-form
      v-model="formData"
      v-bind="formConfig"
      :request-fn="handleRequest"
      cancel-btn-text="取消"
      :is-show-cancel-btn="true"
      :is-show-back-btn="false"
      @request-success="handleRequestSuccess"
      @cancel="visible = false"
    />
  </el-dialog>
</template>

<script>
import { mediaItemCreate, mediaItemUpdate } from '../../api/wx-news-template.js'
import { form, order } from './init.js'
export default {
  data() {
    return {
      formData: {
        status: 0
      },
      formConfig: {
        formDesc: form,
        order: order
      },
      visible: false,
      uploading: false,
      dataForm: {
        mediaId: '',
        file: '',
        fileName: '',
        mediaType: 'image'
      },
      dataRule: {
        fileName: [
          { required: true, message: '素材名称不能为空', trigger: 'blur' }
        ],
        mediaType: [
          { required: true, message: '素材类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    init(fileType) {
      if (fileType) this.dataForm.mediaType = fileType
      this.visible = true
    },
    handleRequestSuccess() {},
    handleRequest(data) {
      if (data.blocs?.length) {
        data.bloc_id = data.blocs[0]
        data.store_id = data.blocs[1]
      }
      if (!this.dataForm.id) {
        mediaItemCreate(data).then((response) => {
          this.$message.success(response.message)
          this.visible = false
          this.$emit('refreshDataList')
        })
      } else {
        mediaItemUpdate(data).then((response) => {
          this.$message.success(response.message)
          this.visible = false
          this.$emit('refreshDataList')
        })
      }
      return Promise.resolve()
    },
    onFileChange(e) {
      const file = event.currentTarget.files[0]
      this.dataForm.file = file
      this.dataForm.fileName = file.name.substring(0, file.name.lastIndexOf('.'))
      let mediaType = file.type.substring(0, file.type.lastIndexOf('/'))
      if (mediaType === 'audio') mediaType = 'voice'
      this.dataForm.mediaType = mediaType
    }
  }
}
</script>
